﻿using System;
using System.Collections.Generic;
using System.Configuration;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Website;

namespace WebApplication.Finance
{

	/// <summary>
	/// Declaration of CommTemplateLetterEditor class
	/// </summary>
	public partial class CommTemplateLetterEditor : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Nested classes

		[Serializable]
		internal class Model
		{

			/////////////////////////////////////////////////////////
			// Attributes

			public int CommTemplateId;

			public string Filename;

		}

		/////////////////////////////////////////////////////////////
		// Constants

		private const string ModelTag = "ContextModel";

		/////////////////////////////////////////////////////////////
		// Attributes

		private Model ContextModel
		{
			get { return ViewState[ModelTag] as Model; }
			set { ViewState[ModelTag] = value; }
		}

		private bool m_bReloadModel = false;

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected override void OnPreRender(EventArgs e)
		{

			// Call base-class function
			base.OnPreRender(e);

			// Get the model
			Model model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG

			// If need to reload model...
			if (m_bReloadModel)
			{

				// Load summary from repository
				string strName;
				string strFilename;
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{
					CommTemplate.Get(ent, model.CommTemplateId, out strName, out strFilename);
				}
				model.Filename = strFilename;
				txtName.Text = strName;

			}

			// Enable/disable controls
			butRevert.Enabled = (model.CommTemplateId!=0);

			// Show/hide controls
			pnlOverwriteOption.Visible = (model.CommTemplateId != 0);
			pnlFileUpload.Visible = ((chkOverwrite.Checked) || (model.CommTemplateId == 0));

		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

				// Get the context model
				Model model = ContextModel;
#if DEBUG
				Debug.Assert(model != null);
#endif // #if DEBUG

			}
			else
			{

				// Get my application
				MyApplication myApp = MyApplication.BindMyApplication();

				// Recover the template id
				MySession mySession = MySession.BindMySession();
				int? iCommTemplateId = mySession.PullHandover(this);
#if DEBUG
				if (iCommTemplateId == null)
					iCommTemplateId = -1;
#else
				if (iCommTemplateId == null)
					Response.Redirect("~/Finance/CommTemplates.aspx");
#endif // #if DEBUG

				// Check the parameters
				if (iCommTemplateId == -1)
				{

					// NEW LETTER TEMPLATE
					Model model = new Model();
					model.CommTemplateId = 0;
					ContextModel = model;

				}
				else
				{

					// EDIT LETTER TEMPLATE

					// Create the model
					Model model = new Model();
					model.CommTemplateId = iCommTemplateId.Value;
					ContextModel = model;

					// Load the template details
					m_bReloadModel = true;

				}

				// Set colours
				pnlFields.BackColor = myApp.PrimaryWebColor;
				pnlFields.BorderColor = myApp.SecondaryWebColor;

			}

		}

		protected void butTest_Click(object sender, EventArgs e)
		{

			// Development message
			(this.Master as FinanceMaster).ErrorMessage = Definitions.DevelopmentMessage;

		}

		protected void butSave_Click(object sender, EventArgs e)
		{

			// Declaration of local variables
			string strError = null;

			// Validate content
			this.Validate();
			if (!this.IsValid)
			{
				(this.Master as FinanceMaster).ErrorMessage = this.Validators.ToErrorMessage();
				return;
			}

			// Get user id
			MySession mySession = MySession.BindMySession();
			int iUserId = mySession.UserID;
#if DEBUG
			if (iUserId == 0)
				iUserId = 1;
#endif // #if DEBUG

			// Get the context model
			Model model = ContextModel;
#if DEBUG
			Debug.Assert(model != null);
#endif // #if DEBUG

			// Get the template folder
			string strTemplateFolderPath = ConfigurationManager.AppSettings["TemplateRootFolderPath"];
			if (!Directory.Exists(strTemplateFolderPath))
				strError = string.Format("The template folder path \"{0}\" cannot be found.", strTemplateFolderPath);

			// If that worked...
			string strExtension = null;
			if (strError == null)
			{

				// If uploading...
				if ((chkOverwrite.Checked) || (model.CommTemplateId == 0))
				{

					// Check if uploader was submitted
					if ((fileUpload.PostedFile == null) || (fileUpload.PostedFile.ContentLength == 0))
						strError = "Please specify a Word data file.";
					else if (fileUpload.PostedFile.ContentLength > (1024 * 1024 * 1))
						strError = "Too large.  Imported files can be up to 1Mb.";
					else
					{
						strExtension = Path.GetExtension(fileUpload.PostedFile.FileName);
						if (
							(string.Compare(strExtension, ".docx", true) != 0)
						)
							strError = "Only Microsoft Word files in docx format can be imported.";
					}

				}

			}

			// If that worked...
			string strTemplateFilepath = null;
			if (strError == null)
			{

				// If overwriting...
				if( (chkOverwrite.Checked) || (model.CommTemplateId==0) )
					strTemplateFilepath = Path.Combine(strTemplateFolderPath, CommTemplate.ComposeNewTemplateFilename(strExtension));
				else
					strTemplateFilepath = Path.Combine(strTemplateFolderPath,model.Filename);

			}

			// If that worked...
			if (strError == null)
			{

				// If uploading a file...
				bool bReviewSummary = false;
				if ((chkOverwrite.Checked) || (model.CommTemplateId == 0))
				{

					// Upload the file
					fileUpload.PostedFile.SaveAs(strTemplateFilepath);
					bReviewSummary = true;

				}

				// Save the template
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{
					strError = CommTemplate.Set(
						ent, 
						model.CommTemplateId, 
						txtName.Text, 
						strTemplateFilepath,
						bReviewSummary,
						iUserId
					);
				}

			}

			// Update the repository
			if (strError != null)
				(this.Master as FinanceMaster).ErrorMessage = strError;
			else
				Response.Redirect("~/Finance/CommTemplates.aspx");

		}

		protected void butRevert_Click(object sender, EventArgs e)
		{

			// Load the template details
			m_bReloadModel = true;

		}

	}

}